

import java.io.IOException;
import java.util.ArrayList;
import java.util.Dictionary;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.edu.hre.db.dao.SurveyDAO;
import com.google.gson.JsonObject;

/**
 * Servlet implementation class SurveyDo
 */
public class SurveyDo extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public SurveyDo() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request,response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		int topicId=0;
		int userId=0;
		HashMap<Integer,String> m = new HashMap<Integer,String>();
		ArrayList<Integer> answerIdAddList = new ArrayList<Integer>();
		Enumeration paramNames = request.getParameterNames();
	    while(paramNames.hasMoreElements()) {
	      String paramName = (String)paramNames.nextElement();
	      if (paramName.equals("topicId")){
	    	  topicId = Integer.parseInt(request.getParameterValues(paramName)[0]);
	      }
	      else if (paramName.equals("userId")){
	    	  userId = Integer.parseInt(request.getParameterValues(paramName)[0]);
	      }
	      else if(paramName.contains("_freetext")){
	    	  m.put(Integer.parseInt(paramName.replace("_freetext", "")), request.getParameterValues(paramName)[0]);
	      }
	      else{
	    	  String[] paramValues = request.getParameterValues(paramName);
	    	  for(int i=0; i<paramValues.length; i++) {
	    		  if (paramValues[i] != "" && !paramName.contains("_dc"))
	    		  answerIdAddList.add(Integer.parseInt(paramValues[i]));
	            }
	      }
	    }
	    new SurveyDAO().InsertSurveyAnswer(topicId,userId,answerIdAddList,m);  
	    JsonObject myObj = new JsonObject();
		myObj.addProperty("success", true);
	    response.getWriter().println(myObj.toString()); 
	    response.getWriter().close();
	}

}
